package main

import (
	"math"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
)

func deleteObj(s []fyne.CanvasObject, o fyne.CanvasObject) (objs []fyne.CanvasObject) {
	for i := 0; i < len(s); i++ {
		if s[i] == o {
			objs = append(objs, s[:i]...)
			objs = append(objs, s[i+1:]...)
		}
	}
	return
}

func layoutLine(x1, y1, x2, y2 float32, l *canvas.Line) {
	l.Position1 = fyne.NewPos(x1, y1)
	l.Position2 = fyne.NewPos(x2, y2)
	l.StrokeWidth = 2
}

// Position1绕Position2旋转，theta为正时，顺时针，theta为负时，逆时针
func RotateLine12(l *canvas.Line, theta float64) {
	x1 := l.Position1.X
	y1 := l.Position1.Y
	x2 := l.Position2.X
	y2 := l.Position2.Y
	l.Position1.X = (x1-x2)*float32(math.Cos(theta)) - (y1-y2)*float32(math.Sin(theta)) + x2
	l.Position1.Y = (x1-x2)*float32(math.Sin(theta)) + (y1-y2)*float32(math.Cos(theta)) + y2
	l.Refresh()
}

// Position1绕Position2旋转，theta为正时，顺时针，theta为负时，逆时针
func RotateLine(l *canvas.Line, theta float64) {
	x1 := l.Position1.X
	y1 := l.Position1.Y
	x2 := l.Position2.X
	y2 := l.Position2.Y
	centerx, centery := (x1+x2)/2, (y1+y2)/2
	// xm:=x2-x1
	// ym:=y2-y1
	// lenn:=math.Sqrt(float64(xm*xm+ym*ym))
	l.Position1.X = (x1-centerx)*float32(math.Cos(theta)) - (y1-centery)*float32(math.Sin(theta)) + centerx
	l.Position1.Y = (x1-centerx)*float32(math.Sin(theta)) + (y1-centery)*float32(math.Cos(theta)) + centery
	l.Position2.X = (x2-centerx)*float32(math.Cos(theta)) - (y2-centery)*float32(math.Sin(theta)) + centerx
	l.Position2.Y = (x2-centerx)*float32(math.Sin(theta)) + (y2-centery)*float32(math.Cos(theta)) + centery
	l.Refresh()
}

// Position2绕Position1旋转，theta为正时，顺时针，theta为负时，逆时针
func RotateLine21(l *canvas.Line, theta float64) {
	x1 := l.Position1.X
	y1 := l.Position1.Y
	x2 := l.Position2.X
	y2 := l.Position2.Y
	l.Position2.X = (x2-x1)*float32(math.Cos(theta)) - (y2-y1)*float32(math.Sin(theta)) + x1
	l.Position2.Y = (x2-x1)*float32(math.Sin(theta)) + (y2-y1)*float32(math.Cos(theta)) + y1
	l.Refresh()
}

// Position2绕Position1旋转，theta为正时，顺时针，theta为负时，逆时针
func RotatePoint(x1, y1, theta float64,x2, y2 *float64) () {
	_=(*x2-x1)*(math.Cos(theta)) - (*y2-y1)*(math.Sin(theta)) + x1
	_=(*x2-x1)*(math.Sin(theta)) + (*y2-y1)*(math.Cos(theta)) + y1
}

func NewLine(x1, y1, r, a float32) *canvas.Line {
	l := canvas.NewLine(red)
	l.Position1 = fyne.Position{X: x1, Y: y1}
	x2, y2 := getCoord(float64(x1), float64(y1), float64(r), float64(a))
	l.Position2 = fyne.Position{X: x2, Y: y2}
	return l
}

// =========================================================================
// Get coordinates of end of a vector, pivot at x,y, length r, angle a(Degree)
// =========================================================================
// Coordinates are returned to caller via the xp and yp pointers
// 垂直向上为0度，垂直向右为90度
const RAD2DEG = 0.0174532925

func getCoord(x, y, r, a float64) (xp, yp float32) {
	sx1 := math.Cos((a - 90) * RAD2DEG)
	sy1 := math.Sin((a - 90) * RAD2DEG)
	xp = float32(sx1*r + x)
	yp = float32(sy1*r + y)
	return
}
